// 预加载运行时配置（dotenv + module-alias 映射逻辑）
import '../config';

import logger from 'jet-logger';

import ENV from '@src/common/constants/ENV';
import server from './server';
import { DatabaseUtils } from '@src/common/db-utils';


/******************************************************************************
                                Constants
******************************************************************************/

const SERVER_START_MSG = (
  'Express server started on port: ' + ENV.Port.toString()
);


/******************************************************************************
                                  Run
******************************************************************************/

// 启动服务器前检查数据库连接
async function startServer() {
  try {
    // 检查数据库连接
    const isDbConnected = await DatabaseUtils.checkConnection();
    if (!isDbConnected) {
      logger.err('Database connection failed. Please check your DATABASE_URL in .env file.');
      process.exit(1);
    }
    logger.info('Database connection successful');

    // Start the server
    server.listen(ENV.Port, err => {
      if (err) {
        logger.err(err.message);
        process.exit(1);
      } else {
        logger.info(SERVER_START_MSG);
      }
    });
  } catch (error) {
    logger.err('Failed to start server:', error);
    process.exit(1);
  }
}

// 启动服务器
startServer();
